﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ProTrack.Api.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Filters
{
    /// <summary>
    /// 全局错误捕获过滤器
    /// </summary>
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        public GlobalExceptionFilter(LogHelper LogHelper)
        {
            this.LogHelper = LogHelper;
        }

        public LogHelper LogHelper { get; }


        /// <summary>
        /// 捕获异常
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {

            await LogHelper.WriteErrorLog("异常全局捕获", context.Exception, context.HttpContext);
            var data = new JsonResult(new
            {
                Data = "[]",
                Code = -1,
                Msg = "请求错误：" + context.Exception.Message
            });
            context.Result = data;

            //已处理
            context.ExceptionHandled = true;

        }

       
    }

}
